//
//  BKUserModifyNickNameViewController.m
//  bestkeep
//
//  Created by windCould on 16/12/8.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKUserModifyNickNameViewController.h"
#import "BKMyCommon.h"
#import "BKUserStatusInfo.h"
#import "BKUserUnitRequestAPI.h"
@interface BKUserModifyNickNameViewController ()<UITextFieldDelegate>

@property (nonatomic,strong)UIView * bgView;
@property (nonatomic,strong)UITextField * nickNameTextField;
@property (nonatomic,strong)UILabel * tipLab;
@property (nonatomic,strong)NSString * oldNickName;


@end

@implementation BKUserModifyNickNameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.view.backgroundColor = ThemeBackgroundColor;
    self.navigationItem.title = BKMyLocalizedString(@"BKUserMyAlterName");
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(contentEditing) name:UITextFieldTextDidChangeNotification object:nil];
    
    [self setUpViews];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
    _oldNickName = userInfo.nickName;
    _nickNameTextField.text = userInfo.nickName;
}

#pragma mark =========================Function===================================

-(void)rightBtnClick:(UIButton *)btn
{
    [self.view endEditing:YES];
    
    if ([self.nickNameTextField.text isEqualToString:self.oldNickName]) {
        
        NSLog(@"新昵称不能跟旧昵称相同");
        [HUD showErrorMessage:@"新昵称不能跟旧昵称相同"];
        return;
    }
    
    if ([self.nickNameTextField.text isEqualToString:@""]) {
        
        NSLog(@"修改昵称不能为空");
        [HUD showErrorMessage:@"修改昵称不能为空"];
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI modifyUserNickNameWithNewNickName:_nickNameTextField.text resultBlcok:^(id obj, NSError *error) {
        
        [BKIndicationView dismiss];
        if (obj) {
            
            BKUserRequestResultModel * result = obj;
            if ([result.success isEqualToString:@"1"]) {
                
                BKUserStatusInfo * userInfo = [BKUserStatusInfo currentUser];
                
                [userInfo.realm beginWriteTransaction];
                userInfo.nickName = weakSelf.nickNameTextField.text;
                [userInfo.realm commitWriteTransaction];
                NSLog(@"昵称修改成功");
                [HUD showSuccessMessage:@"昵称修改成功"];
                [self.navigationController popViewControllerAnimated:YES];
            } else {
            
                NSLog(@"%@",result.msg);
                [HUD showErrorMessage:result.msg];
            }
            
        } else {
        
            NSLog(@"网络请求失败");
            [HUD showErrorMessage:@"网络请求失败"];
        }
        
    }];
    
}

-(void)contentEditing
{
    NSInteger textLength = self.nickNameTextField.text.length;
    if (textLength >15 ) {
        
        self.nickNameTextField.text = [self.nickNameTextField.text substringToIndex:15];
    }

}

#pragma mark =========================布局========================================

-(void)setUpViews{
    
    _bgView = [[UIView alloc]init];
    _bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_bgView];
    
    _nickNameTextField = [[UITextField alloc] init];
    _nickNameTextField.borderStyle = UITextBorderStyleNone;
    _nickNameTextField.backgroundColor = [UIColor whiteColor];
    _nickNameTextField.placeholder = @"请输入昵称";
    _nickNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    _nickNameTextField.textAlignment = NSTextAlignmentLeft;
    _nickNameTextField.keyboardType = UIKeyboardTypeDefault;
    _nickNameTextField.delegate = self;
    [self.view addSubview:_nickNameTextField];

    _tipLab = [UILabel new];
    _tipLab.text = @"最多15个字符，可由中英文，数字“_”组成，24小时可修改一次";
    _tipLab.numberOfLines = 0;
    _tipLab.font = [UIFont systemFontOfSize:10.0];
    _tipLab.textColor = HexColor(0x888888);
    [self.view addSubview:_tipLab];

    [self createRightButton];
    [self layoutViews];
}

-(void)layoutViews{
    
    [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.view.mas_top).offset(10);
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.width.mas_equalTo(@(10));
        make.height.mas_equalTo(@(49));
    }];
    
    [_nickNameTextField mas_makeConstraints:^(MASConstraintMaker *make) {
     
        make.top.mas_equalTo(self.view.mas_top).offset(10);
        make.right.mas_equalTo(self.view.mas_right).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(10);
        make.height.mas_equalTo(@(49));
    }];
  
    [_tipLab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(_nickNameTextField.mas_bottom).offset(5);
        make.left.mas_equalTo(self.view.mas_left).offset(ApplicationBackGauge);
        make.right.mas_equalTo(self.view.mas_right).offset(-ApplicationBackGauge);
    }];
    
}

- (void)createRightButton
{
    UIButton* rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 40, 20);
    [rightBtn setTitle:@"确定" forState:UIControlStateNormal];
    [rightBtn setTitleColor:RGBCOLOR(0, 186, 156,1) forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
}


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    string = @"";
    if ([textField.text isEqualToString:@""] && range.length > 0) {
        //删除字符肯定是安全的
        return YES;
    }
    else {
        
        if (textField.text.length - range.length + string.length > 14) {
            
            return NO;
        }
        else {
            
            return YES;
        }
    }

}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return  YES;
}

@end
